﻿package net.wangit.dev.chart;

import java.util.List;

import net.wangit.context.ActionContext;
import net.wangit.dev.ColumnRowUtil;
import net.wangit.dev.DomainAction;
import net.wangit.dev.LockUtil;
import net.wangit.dev.VersionUtil;
import net.wangit.dev.version.ChartVersion;
import net.wangit.dev.version.Version;
import net.wangit.jdbc.ColumnRow;
import net.wangit.jdbc.DB;
import net.wangit.jdbc.Table;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;
import net.wangit.view.chart.ChartCache;


public class SaveChartAction extends DomainAction {

	private static Version version = new ChartVersion();

	public SaveChartAction() {
	}

	public void doAction(DB db, ActionContext ac) throws Exception {
		String newChartId = ac.getRequestParameter("cf.cid");
		if (!Checker.isEmpty(newChartId))
			newChartId = StringUtil.clearSpace(newChartId.toLowerCase());
		format(ac, newChartId);
		super.doAction(db, ac);
		ac.setSessionAttribute(ChartUI.KEY, newChartId);
		String oldChartId = ac.getRequestParameter("cf.cid.k");
		if (!Checker.isEmpty(oldChartId) && oldChartId.equals(newChartId))
			ac.getActionResult().setScript(null);
		ChartCache.clear(domain, oldChartId);
		ChartReferenceUtil.update(db, domain, oldChartId, newChartId);
		VersionUtil.saveVersion(ac, version, domain, newChartId);
	}

	private void format(ActionContext ac, String chartId) {
		List<Table> tables = ac.getTables();
		if (tables.size() > 0) {
			Table table = tables.get(0);
			List<ColumnRow> rows = table.getRows();
			if (rows.size() > 0) {
				ColumnRow row = rows.get(0);
				row.set("cid", chartId);
				ColumnRowUtil.clearSpace(row, "d");
				LockUtil.setFields(ac, row, "cf");
			}
		}
	}

}
